package com.atguigu.springsecurity.handler;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.utils.R;
import com.atguigu.springsecurity.utils.ResponseResult;
import com.atguigu.springsecurity.utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局异常把你异常捕获了，然后我们需要手动捕获，注意这里还不够完善如果是其他问题应该还要有其他的异常处理(所以可以自定义一个全局异常处理，如果不是这两个就打印我们全局异常处理的结果)
 * 授权过程中出现的异常
 * 然后要将其加入到spring security
 */

@Component // 放进容器里面
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 处理异常
        ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(), "权限不足");
        String res = JSON.toJSONString(result);
        WebUtils.renderString(response,res);
    }
}
